using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Framework.Library.Core.Utils.Web.UI.Controls
{
    public class BaseRegularExpressionValidator : BaseValidator
    {
        internal string ValidationExpression
        {
            get { return (string) ViewState["ValidationExpression"] ?? string.Empty; }
            set
            {
                try
                {
                    Regex.IsMatch(string.Empty, value);
                }
                catch (Exception exception)
                {
                    throw new HttpException(string.Format("{0} is not a valid regular expression.", value), exception);
                }

                ViewState["ValidationExpression"] = value;
            }
        }

        internal static void AddExpandoAttribute(Page page, HtmlTextWriter writer, string controlId,
                                                 string attributeName, string attributeValue, bool encode)
        {
            if (writer != null)
                writer.AddAttribute(attributeName, attributeValue, encode);
            else
                page.ClientScript.RegisterExpandoAttribute(controlId, attributeName, attributeValue, encode);
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            if (RenderUplevel)
            {
                string controlId = ClientID;
                HtmlTextWriter writer2 = ControlUtils.EnableLegacyRendering ? writer : null;
                AddExpandoAttribute(Page, writer2, controlId, "evaluationfunction",
                                    "RegularExpressionValidatorEvaluateIsValid", false);

                if (ValidationExpression.Length > 0)
                    AddExpandoAttribute(Page, writer2, controlId, "validationexpression", ValidationExpression, true);
            }
        }

        protected override bool EvaluateIsValid()
        {
            string input = GetControlValidationValue(ControlToValidate);

            if (input == null || input.Trim().Length == 0)
                return true;

            try
            {
                Match match = Regex.Match(input, ValidationExpression);
                return (match.Success && match.Index == 0 && match.Length == input.Length);
            }
            catch
            {
                return true;
            }
        }
    }
}